package loupan

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Database/admin/loupan_db"
	"hft/Http/Services/base"
	"hft/Http/Services/loupan/loupan_model"
	"hft/e"
	"hft/global"
	"hft/tools"
	"regexp"
)

type PlatForm struct{}

// 平台
func (*PlatForm) Add(data *loupan_db.Platform, claims tools.BaseClaims) (err error) {
	account, err := base.FindAccount(claims, global.OC_DB)
	if err != nil {
		return err
	}
	var lou *admin.LouPan
	err = global.OC_DB.First(&lou, data.LouPanID).Error
	if err != nil {
		return errors.New(e.LouPanNotExist)
	}
	if match, _ := regexp.MatchString(fmt.Sprintf("^%v", account.RegionLink), lou.RegionLink); !match {
		return errors.New(e.NoRightToOpera)
	}
	if res := global.OC_DB.Where("lou_pan_id = ? AND name = ?", data.LouPanID, data.Name).FirstOrCreate(&data); res.RowsAffected == 0 || res.Error != nil {
		return errors.New(e.PlatFormHasExist)
	}
	return nil
}

func (*PlatForm) Edit(data *loupan_db.Platform, claims tools.BaseClaims) (err error) {
	account, err := base.FindAccount(claims, global.OC_DB)
	if err != nil {
		return err
	}
	var lou *admin.LouPan
	err = global.OC_DB.First(&lou, data.LouPanID).Error
	if err != nil {
		return errors.New(e.LouPanNotExist)
	}
	if match, _ := regexp.MatchString(fmt.Sprintf("^%v", account.RegionLink), lou.RegionLink); !match {
		return errors.New(e.NoRightToOpera)
	}
	if res := global.OC_DB.Model(&loupan_db.Platform{}).Where("id = ?", data.ID).Omit("update_time").Updates(map[string]interface{}{
		"name":       data.Name,
		"settlement": data.Settlement,
		"Commission": data.Commission,
	}); res.RowsAffected == 0 || res.Error != nil {
		return errors.New(e.PlatFormHasExist)
	}
	return nil
}

func (*PlatForm) List(louPanID int) (list []*loupan_db.Platform, err error) {
	var data = make([]*loupan_db.Platform, 0)
	global.OC_DB.Where("lou_pan_id = ?", louPanID).Order("sort desc").Find(&data)

	return data, nil
}

func (*PlatForm) Delete(claims tools.BaseClaims, deleteBody loupan_model.DeletePlat) (err error) {

	account, err := base.FindAccount(claims, global.OC_DB)
	if err != nil {
		return err
	}
	var lou *admin.LouPan
	err = global.OC_DB.First(&lou, deleteBody.LouPanID).Error
	if err != nil {
		return errors.New(e.LouPanNotExist)
	}
	if match, _ := regexp.MatchString(fmt.Sprintf("^%v", account.RegionLink), lou.RegionLink); !match {
		return errors.New(e.NoRightToOpera)
	}
	if err = global.OC_DB.Unscoped().Delete(&loupan_db.Platform{}, deleteBody.Ids).Error; err != nil {
		return errors.New(e.ErrorInfo)
	}
	return nil
}

var PlatFormService = new(PlatForm)
